/*
ont-space - The ontology-based resource metadata repository
Copyright (c) 2006-2008, Information Eng. Research Unit - Univ. of Alcalá
http://www.cc.uah.es/ie
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License along
with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
package org.ontspace.util.translator.lom2owl.examples;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.ieee.ltsc.lom.LOM;
import org.ieee.ltsc.lom.jaxb.lomxml.LOM_JAXBContext;
import org.ontspace.MetadataRecordReference;
import org.ontspace.MetadataRepository;
import org.ontspace.lom.owl.LOMQueryManagerImpl;
import org.ontspace.nav.owl.util.RepositoryCreation;
import org.ontspace.owl.MetadataRepositoryFactory;
import org.ontspace.owl.util.MetadataRepositoryConfigException;
import org.ontspace.owl.util.OntologyNotInRepositoryException;
import org.ontspace.owl.util.OspaceConfiguration;
import org.ontspace.util.translator.lom2owl.adapter.vCardAdapter;

/**
 *
 * @author elena
 */
public class ExampleStoringAndTranslateMetadataFromFolder {

    private static LOM lo;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws MetadataRepositoryConfigException,
            IOException, OntologyNotInRepositoryException {
        // TODO code application logic here

        String ontFile, outFile, contentDir, configFile;

        String configFileOspace =
                new String();

        //it is possible to set up the parameters using the command line
        if (args.length < 4) {
            System.out.println(
                    "Four parameters must been set up to use the program: ontFile, outFile, " +
                    "contentDir and configFile.");
            System.out.println(
                    "Using the default values for the mandatory parameters.");
            ontFile =
                    new String(System.getProperty("user.dir") + System.getProperty(
                    "file.separator") + "lom2owl_etc" +
                    System.getProperty("file.separator") + "LOM2OWL.owl");
            Calendar cal =
                    Calendar.getInstance(new Locale("es"));
            SimpleDateFormat sdf =
                    new SimpleDateFormat("dd_MM_yyyy");
            outFile =
                    new String(System.getProperty("user.dir") + System.getProperty(
                    "file.separator") + "lom2owl_etc" +
                    System.getProperty("file.separator") + "output.owl");
            contentDir =
                    new String(System.getProperty("user.dir") +
                    System.getProperty("file.separator") + "lom2owl_etc" +
                    System.getProperty("file.separator") + "Metadatos");
            configFile =
                    new String(System.getProperty("user.dir") +
                    System.getProperty("file.separator") + "lom2owl_etc" +
                    System.getProperty("file.separator") + "config.xml");
            configFileOspace =
                    new String(System.getProperty("user.dir") +
                    System.getProperty("file.separator") + "Metadatos");

        } else {

            System.out.println("Using the values obtained in the command line.");
            ontFile =
                    args[0];
            outFile =
                    args[1];
            contentDir =
                    args[2];
            configFile =
                    args[3];
            configFileOspace =
                    args[4];
        }
        System.out.println(" - ontFile: " + ontFile);
        System.out.println(" - outFile: " + outFile);
        System.out.println(" - contentDir: " + contentDir);
        System.out.println(" - configFile: " + configFile);
        System.out.println(" - configFileOspace: " + configFileOspace);


        OspaceConfiguration configuration =
                null;
        try {
            configuration =
                    new OspaceConfiguration(configFileOspace);
        } catch (URISyntaxException ex) {
            Logger.getLogger(RepositoryCreation.class.getName()).
                    log(Level.SEVERE, null, ex);
        } catch (Exception e) {
            e.printStackTrace();
        }
        HashMap params =
                configuration.getParams();
        HashMap configParams =
                configuration.getQMParams();

        MetadataRepository rep =
                MetadataRepositoryFactory.openMetadataRepository(params);

        LOMQueryManagerImpl qm =
                (LOMQueryManagerImpl) rep.getQueryManager("org.ontspace.lom.owl.LOMQueryManagerImpl",
                configParams);

        System.out.println(rep.getRepositoryURI());


        InputStream lomXmlFile =
                null;

        File dir =
                new File(contentDir);
        File path =
                new File(contentDir + "\\Results");
        deleteDirectory(path);
        List AList =
                new ArrayList();
        if (dir.isDirectory()) {
            if (!dir.exists()) {
                System.out.println("Error: The Directory not exists");
            }
            String[] files =
                    dir.list();
            for (int i =
                    0; i < files.length; i++) {
                AList.add(files[i]);
                System.out.println("File to store: " + files[i]);
            }
        }

        for (int i =
                0; i < AList.size(); i++) {
            String FichName =
                    "";
            FichName =
                    (String) AList.get(i);
            String lomXmlFilePath =
                    null;

            try {
                vCardAdapter vCard =
                        new vCardAdapter();
                lomXmlFilePath =
                        vCard.adaptVCard(FichName, contentDir);
            //      } catch (IOException e) {
            //        e.printStackTrace();
            } catch (Exception e) {

            }


            try {
                lomXmlFile =
                        new FileInputStream(lomXmlFilePath);
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            try {


                LOM lom =
                        parseLOMXML(lomXmlFile);

                MetadataRecordReference storeNewLearningObject =
                        qm.storeNewLearningObject(lom,
                        configFile);

                System.out.println(" Succesful storage! ->" + FichName);
                System.out.println("LO Stored: " +
                        storeNewLearningObject.getLocalMetadataRecordId() + "  " +
                        storeNewLearningObject.getMRRAccessInterface() + "");


//                FileWriter writer2 = new FileWriter("C:/Carga/resultadosCarga"+(i+1)+".txt"); 
//                PrintWriter output2 = new PrintWriter(writer2);
//                 
//                System.out.println("**************** Instances stored: "+(i+1)); 
//                java.util.Calendar cal2 = java.util.Calendar.
//                        getInstance(java.util.Locale.FRANCE);
//                java.util.Date date2 = cal2.getTime();
//                java.text.DateFormat formateadorHora2 = java.text.DateFormat.
//                        getTimeInstance(java.text.DateFormat.MEDIUM);
//                java.text.DateFormat formateadorFecha2 = java.text.DateFormat.
//                        getDateInstance(java.text.DateFormat.MEDIUM);
//                System.out.println(" TIME->"+formateadorHora2.format(date2));
//                output2.println("**************** Instances stored: "+(i+1)); 
//                output2.println(" TIME->"+formateadorHora2.format(date2)); 
//                output2.close(); 

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        qm.close();

    }

    /**
     * This method receives a LOM XML FILE and creates a LOM Object that 
     * stores its content. 
     * 
     */
    private final static LOM parseLOMXML(final InputStream is) throws JAXBException {

        final JAXBContext jaxbContext =
                JAXBContext.newInstance(System.getProperty(LOM_JAXBContext.CONTEXT_PATH_PROP,
                LOM_JAXBContext.DEFAULT_CONTEXT_PATH));

        final Unmarshaller unmarshaller =
                jaxbContext.createUnmarshaller();
        unmarshaller.setValidating(false);

        return (LOM) unmarshaller.unmarshal(is);

    }

    /**
     * This method parse in a LOM object from a LOM-XML file. 
     * 
     */
    protected static void createLOMFromInputStream(InputStream metadataIS)
            throws Exception {

        lo =
                parseLOMXML(metadataIS);

        System.out.println("");
        System.out.println("*************************************************" +
                "***************************");
        System.out.println("*  LOM XML FILE:                                 " +
                "                          *");
        System.out.println("*                                                " +
                "                          *");
        try {
            printLOMXML(lo, System.out);
        } catch (Throwable t) {
            t.printStackTrace();
            return;
        }

        System.out.println("*                                                " +
                "                          *");
        System.out.println("*************************************************" +
                "***************************");

    }
    //    
//    protected void createLOMfromInputStream(InputStream metadataIS)
//            throws Exception {
//
//        lom = parseLOMXML(metadataIS);
//
//
//    }
    private final static void printLOMXML(final LOM lom,
            final OutputStream outputStream) throws JAXBException {

        final JAXBContext jaxbContext =
                JAXBContext.newInstance(System.getProperty(LOM_JAXBContext.CONTEXT_PATH_PROP,
                LOM_JAXBContext.DEFAULT_CONTEXT_PATH));
        final Marshaller marshaller =
                jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(lom, outputStream);
        System.out.println();
        return;

    }

    public static void deleteDirectory(File path) {
        if (path.exists()) {
            File[] files =
                    path.listFiles();
            for (int i =
                    0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    deleteDirectory(files[i]);
                } else {
                    files[i].delete();
                }
            }
        }
        path.delete();
        return;
    }
}
